﻿using QuickRunCore.Helper;
using QuickRunCore.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace QuickRunCore
{
    public partial class FrmMain : Form
    {
        public delegate void MyEventHandler(object sender, MyEventArgs e);

        public event MyEventHandler HotKeyUp;

        FrmSetup _frmSetup;

        /// <summary>
        /// 系统配置信息
        /// </summary>
        ConfigModel Config;

        /// <summary>
        /// 当前选中的分组
        /// </summary>
        Models.ShortcutGroupModel SelectGroup;
        /// <summary>
        /// 分组信息列表
        /// </summary>
        List<Models.ShortcutGroupModel> ShortcutGroupList { get; set; }
        /// <summary>
        /// 当前选中的图标面板
        /// </summary>
        FlowLayoutPanel SelectShortcutPanel;


        /// <summary>
        /// 标题面板背景色
        /// </summary>
        private Color PanelTitleBackColor { get; set; }

        /// <summary>
        /// 左侧面板边框颜色
        /// </summary>
        private Color PanelLeftBackColor { get; set; }

        /// <summary>
        /// 中间面板边框颜色
        /// </summary>
        private Color PanelCenterBackColor { get; set; }

        /// <summary>
        /// 选中的分组颜色
        /// </summary>
        private Color GroupSelectBackColor { get; set; }

        public FrmMain()
        {
            InitializeComponent();

            #region 右下角拖动窗体大小

            this.btnRightBottom.MouseDown += (s, e) =>
            {
                this.bDragging = true;
                this.mPoint = new Point(e.X, e.Y);
            };
            this.btnRightBottom.MouseMove += (s, e) =>
            {
                Point p = new Point(e.X, e.Y);
                Rectangle r = this.ClientRectangle;
                if (bDragging)
                {

                    int w = this.Size.Width;
                    int h = this.Size.Height;
                    w += (e.X - mPoint.X);
                    h += (e.Y - mPoint.Y);
                    this.Size = new Size(w, h);
                    this.Invalidate();

                }
            };
            this.btnRightBottom.MouseUp += (s, e) => { bDragging = false; };

            #endregion

            this.pnlGroupWidth.MouseDown += (s, e) =>
            {
                this.bDragging = true;
                this.mPoint = new Point(e.X, e.Y);
            };
            this.pnlGroupWidth.MouseMove += (s, e) =>
            {
                Point p = new Point(e.X, e.Y);
                Rectangle r = this.ClientRectangle;
                if (bDragging)
                {

                    int w = this.pnlGroup.Width;
                    w += (e.X - mPoint.X);
                    if (w < 100)
                    {
                        w = 100;
                    }
                    if (Config.GroupWidth != w)
                    {
                        Config.GroupWidth = w;
                        SaveConfigInfo();
                    }

                    this.pnlGroup.Width = w;
                }
            };
            this.pnlGroupWidth.MouseUp += (s, e) => { bDragging = false; };


            this.picClose.MouseEnter += (s, e) => { this.picClose.Image = Properties.Resources.BtnClose2; };
            this.picClose.MouseLeave += (s, e) => { this.picClose.Image = Properties.Resources.BtnClose1; };

            //FormBorderStyle为None,拖放窗体
            pnlTitle.MouseDown += (s, a) =>
            {
                ReleaseCapture();
                SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
            };
        }

        #region FormBorderStyle为None,拖放窗体

        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;

        //拖动右下角图标用变量
        bool bDragging;
        Point mPoint;

        #endregion

        private void FrmMain_Load(object sender, EventArgs e)
        {
            //MessageBox.Show(FileHelper.GetProcDir());

            //面板背景色
            PanelTitleBackColor = System.Drawing.Color.FromArgb(30, 115, 155);
            PanelLeftBackColor = System.Drawing.Color.FromArgb(30, 115, 155);
            PanelCenterBackColor = System.Drawing.Color.FromArgb(250, 250, 250);
            GroupSelectBackColor = System.Drawing.Color.FromArgb(23, 86, 117);

            //读取配置文件
            string _sv = FileHelper.ReadFileInfo(FileHelper.GetProcDir() + @"\ConfigInfo");
            if (!string.IsNullOrWhiteSpace(_sv))
            {
                if (!string.IsNullOrWhiteSpace(_sv))
                {
                    Config = JsonHelper.GetObjectFromJsonStr<ConfigModel>(_sv);
                }
            }
            if (Config == null)
            {
                Config = new ConfigModel();
                Config.MouseMiddleOpen = true;
                Config.OpenOnMouseXY = true;
            }
            if (Config.OpenOnMouseXY)
            {
                this.VisibleChanged += (s, e) =>
                {
                    FormLocation();
                };
            }


            #region 拖入文件处理

            pnlCenter.AllowDrop = true;
            pnlCenter.DragEnter += (s, de) =>
            {
                de.Effect = DragDropEffects.Link;//拖动时的图标
            };
            pnlCenter.DragDrop += (s, de) =>
            {
                MessageBox.Show("增加快捷方式失败，请先添加分组", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            };

            #endregion

            //启动时自动隐藏窗体
            //注意，这里很重要，使用BeginInvoke调用里面的代码将会在Load执行完毕后调用否则没办法实现因为Load的时候窗体还不显示，当然你可以用Shown事件
            this.BeginInvoke(new Action(() =>
            {
                this.Hide();
                this.Opacity = 1;
            }));

            //加载分组信息
            string _filePath = FileHelper.GetProcDir() + @"\ShortcutInfo"; //FileHelper.GetProcDir() + @"\ShortcutInfo";
            string _s = FileHelper.ReadFileInfo(_filePath);
            if (!string.IsNullOrWhiteSpace(_s))
            {
                ShortcutGroupList = JsonHelper.GetObjectFromJsonStr<List<Models.ShortcutGroupModel>>(_s);
            }
            if (ShortcutGroupList != null && ShortcutGroupList.Count > 0)
            {
                SelectGroup = ShortcutGroupList[0];
                foreach (Models.ShortcutGroupModel _m in ShortcutGroupList)
                {
                    GroupAddContorl(_m);

                }
            }
            if (SelectGroup != null)
            {
                ShortcutPanelSelect(SelectGroup.ID);
            }

            pnlGroup.SizeChanged += (s, ev) =>
            {
                string _namePrefix = "lblGroup";
                foreach (Control _control in this.pnlGroup.Controls)
                {
                    if (_control is Label)
                    {
                        Label _lbl = _control as Label;
                        if (_lbl.Name.Substring(0, _namePrefix.Length) == _namePrefix)
                        {
                            _lbl.Width = (s as FlowLayoutPanel).ClientSize.Width - 5;
                        }
                    }
                }
            };

            this.Top = Config.FormTop;
            this.Left = Config.FormLeft;
            this.Width = Config.FormWidth;
            this.Height = Config.FormHeight;

            if (this.Width < 650)
            {
                Width = 650;
            }
            if (this.Height < 350)
            {
                Height = 350;
            }
            this.MinimumSize = new Size(650, 350);

            this.Resize += (s, me) =>
            {
                if (this.Height != Config.FormHeight || this.Width != Config.FormWidth)
                {
                    Config.FormHeight = this.Height;
                    Config.FormWidth = this.Width;
                    SaveConfigInfo();
                }
            };


            this.LocationChanged += (s, me) =>
            {
                if (this.Top != Config.FormTop || this.Left != Config.FormLeft)
                {
                    Config.FormTop = this.Top;
                    Config.FormLeft = this.Left;
                    SaveConfigInfo();
                }
            };

            if (Config.GroupWidth == 0)
            {
                Config.GroupWidth = 130;
            }
            pnlGroup.Width = Config.GroupWidth;


            #region 增加鼠标钩子，用于监控鼠标中间激活

            if (Config.MouseMiddleOpen)
            {
                MouseHook hook = new MouseHook();
                hook.MouseUp += (s, me) =>
                {
                    mouseHook_MouseUp(me.Button.ToString(), me.X, me.Y);
                };
                hook.Start();
                Application.ApplicationExit += (s, a) =>
                {
                    hook.Stop();
                };
            }

            #endregion

            #region 增加键盘钩子,用于监控键盘热键激活


            KeyboardHook keyhook = new KeyboardHook();
            keyhook.KeyUp += (s, me) =>
            {
                if (HotKeyUp != null)
                {
                    HotKeyUp(this, new MyEventArgs(me.KeyData.ToString()));
                }
                if (_frmSetup == null)
                {
                    FrmSetup.HideWindowFromHotKey(me.KeyData.ToString());
                }


                if (Config.HotKeyOpen)
                {
                    this.lblTitle.Text = (me.KeyData.ToString());
                }

            };
            keyhook.Start();
            Application.ApplicationExit += (s, a) =>
            {
                keyhook.Stop();
            };


            #endregion

            timerHideIcon.Enabled = true;

        }


        /// <summary>
        /// 鼠标中键点击处理
        /// </summary>
        /// <param name="button"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        private void mouseHook_MouseUp(string button, int x, int y)
        {
            //鼠标点击中键弹起时触发
            if (Config.MouseMiddleOpen && button.ToLower() == "middle")
            {
                if (this.Visible)
                {
                    this.Hide();
                }
                else
                {
                    if (Config.OpenOnMouseXY)
                    {
                        this.Top = Convert.ToInt32((y / ScaleY) - Height / 2);
                        this.Left = Convert.ToInt32((x / ScaleX) - Width / 2);
                    }
                    FormShow();
                }

            }

        }


        #region 获取屏幕缩放比

        //  Win32 API
        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr ptr);
        [DllImport("gdi32.dll")]
        static extern int GetDeviceCaps(
        IntPtr hdc, // handle to DC
        int nIndex // index of capability
        );
        [DllImport("user32.dll", EntryPoint = "ReleaseDC")]
        static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc);

        // DeviceCaps常量
        const int HORZRES = 8;
        const int VERTRES = 10;
        const int LOGPIXELSX = 88;
        const int LOGPIXELSY = 90;
        const int DESKTOPVERTRES = 117;
        const int DESKTOPHORZRES = 118;



        /// <summary>
        /// 获取宽度缩放百分比
        /// </summary>
        public static float ScaleX
        {
            get
            {
                IntPtr hdc = GetDC(IntPtr.Zero);
                int t = GetDeviceCaps(hdc, DESKTOPHORZRES);
                int d = GetDeviceCaps(hdc, HORZRES);
                float ScaleX = (float)GetDeviceCaps(hdc, DESKTOPHORZRES) / (float)GetDeviceCaps(hdc, HORZRES);
                ReleaseDC(IntPtr.Zero, hdc);
                return ScaleX;
            }
        }

        /// <summary>
        /// 获取高度缩放百分比
        /// </summary>
        public static float ScaleY
        {
            get
            {
                IntPtr hdc = GetDC(IntPtr.Zero);
                float ScaleY = (float)(float)GetDeviceCaps(hdc, DESKTOPVERTRES) / (float)GetDeviceCaps(hdc, VERTRES);
                ReleaseDC(IntPtr.Zero, hdc);
                return ScaleY;
            }
        }

        #endregion

        /// <summary>
        /// 显示窗体时控制窗体显示位置
        /// </summary>
        private void FormLocation()
        {
            if (this.Width > SystemInformation.WorkingArea.Width / Convert.ToInt32(ScaleX))
            {
                this.Width = SystemInformation.WorkingArea.Width / Convert.ToInt32(ScaleX);
            }
            if (this.Height > SystemInformation.WorkingArea.Height / Convert.ToInt32(ScaleY))
            {
                this.Height = SystemInformation.WorkingArea.Height / Convert.ToInt32(ScaleY);
            }
            if (this.Top < 0)
            {
                this.Top = 0;
            }
            if (this.Left < 0)
            {
                this.Left = 0;
            }
            if ((this.Left + this.Width) > SystemInformation.WorkingArea.Width)
            {
                this.Left = (SystemInformation.WorkingArea.Width - this.Width);
            }
            if ((this.Top + this.Height) > SystemInformation.WorkingArea.Height)
            {
                this.Top = (SystemInformation.WorkingArea.Height - this.Height);
            }
            Config.FormTop = this.Top;
            Config.FormLeft = this.Left;
            Config.FormWidth = this.Width;
            Config.FormHeight = this.Height;
        }

        /// <summary>
        /// 保存系统配置信息
        /// </summary>
        public void SaveConfigInfo()
        {
            FileHelper.SaveFileInfo(FileHelper.GetProcDir() + @"\ConfigInfo", JsonHelper.GetJsonStrFromObject(Config));
        }



        /// <summary>
        /// 隐藏窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }


        #region 分组信息

        /// <summary>
        /// 增加分组控件
        /// </summary>
        /// <param name="id">分组ID</param>
        /// <param name="groupName">分组名称</param>
        private void GroupAddContorl(Models.ShortcutGroupModel group)
        {
            string _namePrefix = "lblGroup";
            Label _lblGroup = new Label();
            this.pnlGroup.Controls.Add(_lblGroup);
            _lblGroup.ForeColor = System.Drawing.Color.White;
            _lblGroup.Location = new System.Drawing.Point(3, 0);
            _lblGroup.Name = _namePrefix + group.ID;
            _lblGroup.Padding = new System.Windows.Forms.Padding(10, 0, 0, 0);
            _lblGroup.Height = 35;
            _lblGroup.Width = pnlGroup.Width;
            _lblGroup.TabIndex = 1;
            _lblGroup.Text = group.GroupName;
            _lblGroup.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            _lblGroup.ContextMenuStrip = menuGroup;
            _lblGroup.Tag = group;
            ShortcutPanelAdd(group);

            _lblGroup.MouseEnter += (s, e) =>
            {
                Label _lbl = s as Label;
                _lbl.BackColor = GroupSelectBackColor;
            };
            _lblGroup.MouseLeave += (s, e) =>
            {
                Label _lbl = s as Label;
                if (SelectGroup != null)
                {
                    if (_lbl.Name != _namePrefix + SelectGroup.ID)
                    {
                        _lbl.BackColor = PanelLeftBackColor;
                    }
                    else
                    {
                        _lbl.BackColor = GroupSelectBackColor;
                    }
                }
                else
                {
                    _lbl.BackColor = PanelLeftBackColor;
                }

            };
            _lblGroup.MouseUp += (s, e) =>
            {
                Label _lbl;

                _lbl = s as Label;
                if (ShortcutGroupList.FindAll(m => m.ID == _lbl.Name.Substring(_namePrefix.Length, _lbl.Name.Length - _namePrefix.Length)).Count == 1)
                {
                    SelectGroup = ShortcutGroupList.Find(m => m.ID == _lbl.Name.Substring(_namePrefix.Length, _lbl.Name.Length - _namePrefix.Length));

                }

                foreach (Control _control in this.pnlGroup.Controls)
                {
                    if (_control is Label)
                    {

                        if (_lbl.Name.Substring(0, _namePrefix.Length) == _namePrefix)
                        {
                            _lbl = (Label)_control;
                            if (_lbl.Name != _namePrefix + SelectGroup.ID)
                            {
                                _lbl.BackColor = PanelLeftBackColor;
                            }
                            else
                            {
                                _lbl.BackColor = GroupSelectBackColor;
                            }
                        }
                    }
                }

                ShortcutPanelSelect(SelectGroup.ID);
            };

            if (SelectGroup.ID == group.ID)
            {
                CallObjectEvent(_lblGroup, "OnMouseUp");
            }

        }

        /// <summary>
        /// 调用控件的事件
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="EventName"></param>
        /// <param name="e"></param>
        private void CallObjectEvent(Object obj, string EventName, EventArgs e = null)
        {
            //建立一个类型       
            Type t = Type.GetType(obj.GetType().AssemblyQualifiedName);
            //产生方法      
            System.Reflection.MethodInfo m = t.GetMethod(EventName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            //参数赋值。传入函数      
            //获得参数资料  
            System.Reflection.ParameterInfo[] para = m.GetParameters();
            //根据参数的名字，拿参数的空值。  
            //参数对象      
            object[] p = new object[1];
            if (e == null)
                p[0] = Type.GetType(para[0].ParameterType.BaseType.FullName).GetProperty("Empty");
            else
                p[0] = e;
            //调用  
            m.Invoke(obj, p);
            return;
        }


        #endregion

        #region 图标面板

        /// <summary>
        /// 增加图标面板
        /// </summary>
        /// <param name="groupID"></param>
        private void ShortcutPanelAdd(ShortcutGroupModel group)
        {
            string _namePrefix = "pnlCenter";
            FlowLayoutPanel _pnlCenter = new FlowLayoutPanel();
            _pnlCenter.BackColor = PanelCenterBackColor;
            _pnlCenter.Dock = System.Windows.Forms.DockStyle.Fill;
            _pnlCenter.Location = new System.Drawing.Point(0, 0);
            _pnlCenter.Name = _namePrefix + group.ID;
            _pnlCenter.Size = new System.Drawing.Size(487, 410);
            _pnlCenter.AutoScroll = true;
            pnlCenter.Controls.Add(_pnlCenter);

            //初始化已添加的快捷方式 
            if (group != null)
            {
                if (group.ShortcutList != null && group.ShortcutList.Count > 0)
                {
                    foreach (ShortcutModel _shortcut in group.ShortcutList)
                    {
                        if(!File.Exists(_shortcut.FilePath))
                        {
                            continue;
                        }

                        string _shortcutID = _shortcut.ID;
                        string _shortcutName = _shortcut.FileName;
                        Icon _icon = ICONHelper.GetFileIcon(_shortcut.FilePath, 0);
                        if (_icon == null)
                        {
                            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmMain));
                            _icon = ((System.Drawing.Icon)(resources.GetObject("commonfile")));
                        }
                        ButtonItemAdd(_pnlCenter, _shortcutID, _shortcutName, _shortcut, _icon);

                    }
                }
            }


            #region 拖入文件处理

            _pnlCenter.AllowDrop = true;
            _pnlCenter.DragEnter += (s, de) =>
            {
                de.Effect = DragDropEffects.Link;//拖动时的图标
            };
            _pnlCenter.DragDrop += (s, de) =>
            {
                if (SelectGroup == null)
                {
                    MessageBox.Show("增加快速启动失败，请先添加分组", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //将外部程序拖放进来时处理 
                foreach (object o in ((System.Array)de.Data.GetData(DataFormats.FileDrop)))
                {
                    string _filePath = o.ToString();
                    if (File.Exists(_filePath) || Directory.Exists(_filePath))
                    {
                        string _fileExt = System.IO.Path.GetExtension(_filePath);
                        string _fileName = System.IO.Path.GetFileNameWithoutExtension(_filePath);
                        if (_fileExt.ToLower() == ".lnk")
                        {
                            IWshRuntimeLibrary.IWshShortcut _shortcut = null;
                            IWshRuntimeLibrary.IWshShell_Class shell = new IWshRuntimeLibrary.IWshShell_Class();
                            _shortcut = shell.CreateShortcut(_filePath) as IWshRuntimeLibrary.IWshShortcut;
                            if (!string.IsNullOrEmpty(_shortcut.TargetPath))
                            {
                                _filePath = _shortcut.TargetPath;
                            }
                        }


                        if (!string.IsNullOrWhiteSpace(_filePath))
                        {
                            //增加图标对象
                            ShortcutModel _shortcut = new ShortcutModel();
                            _shortcut.ID = Guid.NewGuid().ToString().Replace("-", "");
                            _shortcut.FileName = _fileName;
                            _shortcut.FilePath = _filePath;

                            string _shortcutID = _shortcut.ID;
                            string _shortcutName = _shortcut.FileName;
                            Icon _icon = ICONHelper.GetFileIcon(_shortcut.FilePath, 0);
                            if (_icon == null)
                            {
                                System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmMain));
                                _icon = ((System.Drawing.Icon)(resources.GetObject("commonfile")));
                            }
                            SelectGroup.ShortcutList.Add(_shortcut);
                            FileHelper.SaveFileInfo(FileHelper.GetProcDir() + @"\ShortcutInfo", JsonHelper.GetJsonStrFromObject(ShortcutGroupList));

                            ButtonItemAdd(SelectShortcutPanel, _shortcutID, _shortcutName, _shortcut, _icon);
                        }
                    }
                }
            };

            #endregion
        }

        /// <summary>
        /// 选中图标面板
        /// </summary>
        /// <param name="groupID"></param>
        private void ShortcutPanelSelect(string groupID)
        {
            string _namePrefix = "pnlCenter";
            if (this.pnlCenter.Controls.Find(_namePrefix + groupID, false) != null)
            {
                if (SelectShortcutPanel != null)
                {
                    SelectShortcutPanel.Visible = false;
                }
                FlowLayoutPanel _pnlShortcut = this.pnlCenter.Controls.Find(_namePrefix + groupID, false)[0] as FlowLayoutPanel;
                SelectShortcutPanel = _pnlShortcut;
                _pnlShortcut.Visible = true;
            }

        }

        /// <summary>
        /// 增加快捷方式按钮
        /// </summary>
        /// <param name="shortcutID"></param>
        /// <param name="shortcutName"></param>
        /// <param name="tag"></param>
        /// <param name="icon"></param>
        private void ButtonItemAdd(FlowLayoutPanel pnl, string shortcutID, string shortcutName, ShortcutModel tag, Icon icon)
        {
            if (pnl != null)
            {
                ButtonItem _bi = new ButtonItem();
                _bi.Name = "bi" + shortcutID;
                _bi.Text = shortcutName;
                Icon _icon = icon;
                if (_icon == null)
                {
                    return;
                }
                Image _image = _icon.ToBitmap();
                if (_image.Width != 32 && _image.Height != 32)
                {
                    _image = resizeImage(_image, 32, 32);
                }
                _bi.Image = _image;
                _bi.Tag = tag;
                _bi.ContextMenuStrip = menuButtonItem;
                _bi.OnClick += ButtonItemClick;
                pnl.Controls.Add(_bi);
                _bi.OnMouseEnter += (s, e) =>
                {
                    ((s as ButtonItem).Parent as FlowLayoutPanel).AutoScroll = true;
                };

            }

        }

        public enum ShowCommands : int
        {
            SW_HIDE = 0,
            SW_SHOWNORMAL = 1,
            SW_NORMAL = 1,
            SW_SHOWMINIMIZED = 2,
            SW_SHOWMAXIMIZED = 3,
            SW_MAXIMIZE = 3,
            SW_SHOWNOACTIVATE = 4,
            SW_SHOW = 5,
            SW_MINIMIZE = 6,
            SW_SHOWMINNOACTIVE = 7,
            SW_SHOWNA = 8,
            SW_RESTORE = 9,
            SW_SHOWDEFAULT = 10,
            SW_FORCEMINIMIZE = 11,
            SW_MAX = 11
        }
        [DllImport("shell32.dll")]
        static extern IntPtr ShellExecute(
            IntPtr hwnd,
            string lpOperation,
            string lpFile,
            string lpParameters,
            string lpDirectory,
            ShowCommands nShowCmd);

        /// <summary>
        /// 点击快捷方式图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonItemClick(object sender, EventArgs e)
        {
            //EventArgs继承自MouseEventArgs,所以可以强转
            MouseEventArgs Mouse_e = (MouseEventArgs)e;

            //点鼠标右键,return
            if (Mouse_e.Button == MouseButtons.Left)
            {
                ShortcutModel _shortcut = (sender as ButtonItem).Tag as ShortcutModel;
                //System.Diagnostics.Process.Start(_shortcut.FilePath, _shortcut.RunParam);
                string _filedir = GetFileDirectoryName(_shortcut.FilePath) + "\\";
                ShellExecute(IntPtr.Zero, "open", _shortcut.FilePath.Replace(_filedir, ""), _shortcut.RunParam, _filedir, ShowCommands.SW_SHOWNORMAL);
                this.Hide();
            }
        }

        /// <summary>
        /// 获取文件所在文件夹
        /// </summary>
        /// <param name="strPath">文件路径</param>
        /// <returns></returns>
        public static string GetFileDirectoryName(string strPath)
        {
            return Path.GetDirectoryName(strPath);
        }

        /// <summary>
        /// 改变图标尺寸
        /// </summary>
        /// <param name="imgToResize">原图片</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns>修改后的图片</returns>
        private System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, int width, int height)
        {
            //获取图片宽度
            int sourceWidth = imgToResize.Width;
            //获取图片高度
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;
            //计算宽度的缩放比例
            nPercentW = ((float)width / (float)sourceWidth);
            //计算高度的缩放比例
            nPercentH = ((float)height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;
            //期望的宽度
            int destWidth = (int)(sourceWidth * nPercent);
            //期望的高度
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            //绘制图像
            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();
            return (System.Drawing.Image)b;
        }

        #endregion

        /// <summary>
        /// 快捷方式右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuButtonItem_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Name == "miItemEdit")
            {
                ButtonItem _biShortcut = (sender as ContextMenuStrip).SourceControl as ButtonItem;
                ShortcutModel _shortcut = _biShortcut.Tag as ShortcutModel;

                MessageBox.Show("编辑" + _shortcut.FileName);

            }
            else if (e.ClickedItem.Name == "miItemDelete")
            {
                ButtonItem _biShortcut = (sender as ContextMenuStrip).SourceControl as ButtonItem;
                ShortcutModel _shortcut = _biShortcut.Tag as ShortcutModel;
                SelectGroup.ShortcutList.Remove(_shortcut);
                FileHelper.SaveFileInfo(FileHelper.GetProcDir() + @"\ShortcutInfo", JsonHelper.GetJsonStrFromObject(ShortcutGroupList));
                _biShortcut.Dispose();
            }
            else if (e.ClickedItem.Name == "miItemOpenFileDir")
            {
                //打开文件所在目录
                ButtonItem _biShortcut = (sender as ContextMenuStrip).SourceControl as ButtonItem;
                ShortcutModel _shortcut = _biShortcut.Tag as ShortcutModel;

                System.Diagnostics.Process open = new System.Diagnostics.Process();
                open.StartInfo.FileName = "explorer";
                open.StartInfo.Arguments = @"/select," + _shortcut.FilePath;
                open.Start();
            }
        }

        private void menuGroup_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Name == "miGroupAdd")
            {
                FrmAddGroup _frmAddGroup = new FrmAddGroup();
                _frmAddGroup.lblTitle.Text = "增加分组";
                if (_frmAddGroup.ShowDialog() == DialogResult.OK)
                {
                    if (ShortcutGroupList == null)
                    {
                        ShortcutGroupList = new List<Models.ShortcutGroupModel>();
                    }
                    string groupID = Guid.NewGuid().ToString().Replace("-", "");
                    string groupName = _frmAddGroup.txtGroupName.Text;
                    if (!string.IsNullOrWhiteSpace(groupName))
                    {
                        Models.ShortcutGroupModel _lgm = new Models.ShortcutGroupModel() { ID = groupID, GroupName = groupName };
                        ShortcutGroupList.Add(_lgm);
                        FileHelper.SaveFileInfo(FileHelper.GetProcDir() + @"\ShortcutInfo", JsonHelper.GetJsonStrFromObject(ShortcutGroupList));
                        SelectGroup = _lgm;
                        GroupAddContorl(_lgm);
                    }
                }
            }
            else if (e.ClickedItem.Name == "miGroupEdit")
            {
                Label _lblGroup = (sender as ContextMenuStrip).SourceControl as Label;
                Models.ShortcutGroupModel _group = _lblGroup.Tag as Models.ShortcutGroupModel;

                FrmAddGroup _frmAddGroup = new FrmAddGroup();
                _frmAddGroup.lblTitle.Text = "修改分组";
                _frmAddGroup.txtGroupName.Text = _group.GroupName;
                if (_frmAddGroup.ShowDialog() == DialogResult.OK)
                {
                    _group.GroupName = _frmAddGroup.txtGroupName.Text;
                    FileHelper.SaveFileInfo(FileHelper.GetProcDir() + @"\ShortcutInfo", JsonHelper.GetJsonStrFromObject(ShortcutGroupList));
                    _lblGroup.Text = _group.GroupName;
                }

            }
            else if (e.ClickedItem.Name == "miGroupDelete")
            {
                Label _lblGroup = (sender as ContextMenuStrip).SourceControl as Label;
                Models.ShortcutGroupModel _group = _lblGroup.Tag as Models.ShortcutGroupModel;
                if (MessageBox.Show("提示", "该分组存在快捷启动，是否确定删除?", MessageBoxButtons.YesNo) == DialogResult.OK)
                {
                    ShortcutGroupList.Remove(_group);
                    FileHelper.SaveFileInfo(FileHelper.GetProcDir() + @"\ShortcutInfo", JsonHelper.GetJsonStrFromObject(ShortcutGroupList));
                    _lblGroup.Dispose();
                }
            }
        }

        private void menuGroup_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            string sName = (sender as ContextMenuStrip).SourceControl.Name;
            if (sName == "pnlLeft")
            {
                miGroupEdit.Visible = false;
                miGroupDelete.Visible = false;
            }
            else
            {
                miGroupEdit.Visible = true;
                miGroupDelete.Visible = true;
            }
        }

        private void niMain_Click(object sender, EventArgs e)
        {
            //EventArgs继承自MouseEventArgs,所以可以强转  
            MouseEventArgs Mouse_e = (MouseEventArgs)e;

            if (Mouse_e.Button == MouseButtons.Left)
            {
                FormShow();
            }
        }

        /// <summary>
        /// 设置此窗体为活动窗体
        /// </summary>
        /// <param name="hWnd"></param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        /// <summary>
        /// 将窗体移动到最前方
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="fAltTab"></param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        /// <summary>
        /// 隐藏窗体后重新示窗体
        /// </summary>
        private void FormShow()
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;  //窗体状态默认大小
            this.Activate();//激活窗体给予焦点
            this.ShowInTaskbar = true;

            //设置窗体为活动窗体 
            SetForegroundWindow(this.Handle);

            //移动到最前
            SwitchToThisWindow(this.Handle, true);
        }

        /// <summary>
        /// 任务栏菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuMain_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Name == "miOption")
            {
                //设置
                _frmSetup = new FrmSetup();
                _frmSetup.Text = "设置";
                HotKeyUp += new MyEventHandler(_frmSetup.HotKeyUp);
                if (_frmSetup.ShowDialog() == DialogResult.OK)
                {

                }
                _frmSetup.Dispose();
                _frmSetup = null;

            }
            else if (e.ClickedItem.Name == "miClose")
            {
                this.Close();
            }
        }

        private void timerHideIcon_Tick(object sender, EventArgs e)
        {
            timerHideIcon.Enabled = false;
            if (_frmSetup == null)
            {
                FrmSetup.InitIcon();
            }
            timerHideIcon.Enabled = true;
        }
    }
}
